/**
 * 环境监测实验板-蜂鸣器、MQ2燃气传感器、AHT20温湿度传感器
 *  
 *  * 蜂鸣器——PWM控制声音的频率和音量
    * GPIO09: PWM0
    * 
  * MQ2 燃气传感器——ADC读取模拟值
    * GPIO11: ADC5
    * 
  * AHT20 温湿度传感器——I2C接口通信，地址 0x38
    * GPIO13: I2C0_SDA
    * GPIO14: I2C0_SCL
    *参考传感器数据手册编写i2c驱动
    * 
    *程序功能：
    1. 读取燃气传感器的ADC值;
    2. 读取AHT20温湿度传感器的数值;
    3. 温度、湿度上升（哈一口气）蜂鸣器叫几声.
   基于canary2.0 开发. Code By:HelloKun 2021.09.25
*/

#include <stdio.h>
#include <unistd.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_errno.h" //==IOT_SUCCESS =0 
#include <stddef.h>
#include <hi_time.h>

#include <iot_gpio.h>
#include <hi_io.h>
#include <iot_pwm.h>
#include <hi_pwm.h>
#include <hi_adc.h>
#include <hi_i2c.h>
#include "aht20.h"

#define BEEP_PWM  0
#define BEEP_IO   9
#define MQ2_IO    11

static void EnviroTask(void *arg)
{
    (void) arg;
    unsigned int data;
    float temp;
    float humi;
    while(1)
    {  
        if(hi_adc_read(HI_ADC_CHANNEL_5,&data,HI_ADC_EQU_MODEL_1,HI_ADC_CUR_BAIS_DEFAULT, 0)==0) 
        { printf("燃气MQ2 data:%d\n",data);}

       AHT20_Calibrate();
       AHT20_StartMeasure();
       AHT20_GetMeasureResult(&temp, &humi);

       printf(" 温度temp:%.3f ",temp);
       printf(" 湿度humi:%.3f\n",humi);
       if(temp>25) //温度大于25摄氏度，蜂鸣器叫
       {
          IoTPwmStart(BEEP_PWM,90,40000);
       }
       else{
         IoTPwmStop(BEEP_PWM);
       }
    }
   
}

static void EnviroEntry(void)
{
    IoTGpioInit(BEEP_IO);
    hi_io_set_func(BEEP_IO,HI_IO_FUNC_GPIO_9_PWM0_OUT);
    IoTPwmInit(BEEP_PWM);
   
    IoTGpioInit(MQ2_IO);
    hi_io_set_func(MQ2_IO,HI_IO_FUNC_GPIO_5_GPIO);
   
    AHT20_I2C_Init();

    osThreadAttr_t attr;  
    attr.name = "EnviroTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.priority = 24;
    attr.stack_size = 4096;
    if(osThreadNew(EnviroTask,NULL,&attr)==NULL)
    {
        printf("[EnviroEntry] Failed to create EnviroTask!\n ");
    }
}

APP_FEATURE_INIT(EnviroEntry);
